﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace WebChatApi.Common
{
    /// <summary>
    /// Singleton class for Web Utility.
    /// </summary>
    public class WebUtil : Singleton<WebUtil>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WebUtil"/> class.
        /// </summary>
        public WebUtil() { }

        const string zeroCharset = "0";

        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        /// <summary>
        /// Gets ip and mac address by <c>HttpRequest</c> instance.
        /// </summary>
        /// <param name="httpRequest">The <c>HttpRequest</c> instance.</param>
        /// <param name="ipAddress">The string to set ip address.</param>
        /// <param name="macAddress">The string to set mac address.</param>
        public void GetIpAndMacAddressByHttpRequest(HttpRequest httpRequest, out string ipAddress, out string macAddress)
        {
            ipAddress = string.Empty;
            macAddress = string.Empty;

            if (httpRequest != null)
            {
                ipAddress = GetClientIpByHttpRequest(httpRequest);

                int ipDestination = inet_addr(ipAddress);
                Int64 macinfo = new Int64();
                int len = 6;
                int res = SendARP(ipDestination, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                if (mac_src == zeroCharset)
                {
                    return;
                }

                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, zeroCharset);
                }

                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            macAddress = macAddress.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            macAddress = "-" + macAddress.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets client ip by <c>HttpRequest</c> instance.
        /// </summary>
        /// <param name="httpRequest">The <c>HttpRequest</c> instance.</param>
        /// <returns>The ip address.</returns>
        public string GetClientIpByHttpRequest(HttpRequest httpRequest)
        {
            string clientIp = string.Empty;

            if (httpRequest != null)
            {
                clientIp = httpRequest.UserHostAddress.ToString().Trim();
            }

            return clientIp;
        }

        /// <summary>
        /// Generates HttpWebRequest by url.
        /// </summary>
        /// <param name="url">The url string.</param>
        /// <param name="method">The method.</param>
        /// <returns>
        /// The HttpWebRequest instance, or null if fail.
        /// </returns>
        public HttpWebRequest GenerateHttpWebRequestByUrl(string url, string method = "GET")
        {
            HttpWebRequest httpWebRequest = null;

            try
            {
                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Accept = "*";
                httpWebRequest.Method = string.IsNullOrWhiteSpace(method) ? "GET" : method;
            }
            catch { }

            return httpWebRequest;
        }

        /// <summary>
        /// Generates HttpWebRequest by uri.
        /// </summary>
        /// <param name="uri">The <c>Uri</c> instance.</param>
        /// <param name="method">The method.</param>
        /// <param name="cookieContainer">The cookie container.</param>
        /// <returns>The HttpWebRequest instance, or null if fail.</returns>
        public HttpWebRequest GenerateHttpWebRequestByUri(Uri uri, string method = "GET", CookieContainer cookieContainer = null)
        {
            HttpWebRequest httpWebRequest = null;
            try
            {
                httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Accept = "*";
                httpWebRequest.CookieContainer = cookieContainer == null ? new CookieContainer() : cookieContainer;
                httpWebRequest.Method = string.IsNullOrWhiteSpace(method) ? "GET" : method;
            }
            catch { }

            return httpWebRequest;
        }

        /// <summary>
        /// Gets text content from WebResponse by defualt encoding.
        /// </summary>
        /// <param name="webResponse">The WebResponse instance.</param>
        /// <returns>
        /// The content string.
        /// </returns>
        public string ReadTextFromResponse(WebResponse webResponse)
        {
            return ReadTextFromResponse(webResponse, Encoding.Default);
        }

        /// <summary>
        /// Gets text content from WebResponse by specified encoding.
        /// </summary>
        /// <param name="webResponse">The WebResponse instance.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>
        /// The content string.
        /// </returns>
        public string ReadTextFromResponse(WebResponse webResponse, Encoding encoding)
        {
            string result = string.Empty;

            if (webResponse != null)
            {
                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    if (encoding == null)
                    {
                        encoding = Encoding.UTF8;
                    }
                    StreamReader streamReader = new StreamReader(responseStream, encoding);
                    result = streamReader.ReadToEnd();
                }
            }

            return result;
        }

        /// <summary>
        /// Gets web page by url by default encoding.
        /// </summary>
        /// <param name="url">The url string.</param>
        /// <returns>
        /// The content string.
        /// </returns>
        public string GetWebPageByUrl(string url)
        {
            return GetWebPageByUrl(url, Encoding.UTF8);
        }

        /// <summary>
        /// Gets web page by url by specified encoding.
        /// </summary>
        /// <param name="url">The url string.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>
        /// The content string.
        /// </returns>
        public string GetWebPageByUrl(string url, Encoding encoding)
        {
            string content = string.Empty;

            if (!string.IsNullOrWhiteSpace(url))
            {
                content = GetWebPageByUri(new Uri(url), encoding);
            }

            return content;
        }

        /// <summary>
        /// Gets the web page by URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>The content string.</returns>
        public string GetWebPageByUri(Uri uri, Encoding encoding)
        {
            return GetWebPageByUri(uri, encoding, null);
        }

        /// <summary>
        /// Gets web page by uri by default encoding.
        /// </summary>
        /// <param name="uri">The uri.</param>
        /// <param name="encoding">The encoding.</param>
        /// <param name="cookieContainer">The cookie container.</param>
        /// <returns>The content string.</returns>
        private string GetWebPageByUri(Uri uri, Encoding encoding, CookieContainer cookieContainer)
        {
            string content = string.Empty;

            if (uri != null)
            {
                if (cookieContainer == null)
                {
                    cookieContainer = new CookieContainer();
                }

                HttpWebRequest httpWebRequest = GenerateHttpWebRequestByUri(uri);
                if (httpWebRequest != null)
                {
                    WebResponse response = null;

                    try
                    {
                        response = httpWebRequest.GetResponse();
                        content = ReadTextFromResponse(response, encoding);
                    }
                    finally
                    {
                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                }
            }
            return content;
        }

        /// <summary>
        /// Gets the web page by URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        public string GetWebPageByUri(Uri uri)
        {
            return GetWebPageByUri(uri, Encoding.Default);
        }

        #region FillDataOnHttpWebRequest

        /// <summary>
        /// Fills the file data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="dataMappings">The data mappings.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="paramName">Name of the param.</param>
        /// <param name="contentType">Type of the content.</param>
        public void FillFileDataOnHttpWebRequest(HttpWebRequest httpWebRequest, Dictionary<string, string> dataMappings, string fileName, string paramName, string contentType)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            if (httpWebRequest != null)
            {
                httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                httpWebRequest.Method = "POST";
                httpWebRequest.KeepAlive = true;

                Stream stream = httpWebRequest.GetRequestStream();

                string formDataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                foreach (string key in dataMappings.Keys)
                {
                    stream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    string formItem = string.Format(formDataTemplate, key, dataMappings[key]);
                    byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
                    stream.Write(formItemBytes, 0, formItemBytes.Length);
                }
                stream.Write(boundaryBytes, 0, boundaryBytes.Length);

                if (!string.IsNullOrWhiteSpace(fileName) && File.Exists(fileName))
                {
                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                    string header = string.Format(headerTemplate, paramName, fileName, contentType);
                    byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);
                    stream.Write(headerBytes, 0, headerBytes.Length);

                    FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                    fileStream.Close();
                }

                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                stream.Write(trailer, 0, trailer.Length);
                stream.Close();
            }
        }

        /// <summary>
        /// Fills post data on HttpWebRequest.
        /// </summary>
        /// <param name="httpWebRequest">The HttpWebRequest instance.</param>
        /// <param name="method">The method.</param>
        /// <param name="dataMappings">The datas.</param>
        private void FillDataOnHttpWebRequest(HttpWebRequest httpWebRequest, string method, Dictionary<string, string> dataMappings)
        {
            if (httpWebRequest != null)
            {
                StringBuilder sb = new StringBuilder();
                if (dataMappings != null)
                {
                    foreach (string key in dataMappings.Keys)
                    {
                        string value = string.Empty;
                        if (dataMappings[key] != null)
                        {
                            value = dataMappings[key];
                        }
                        sb.Append(key + "=" + value.Trim() + "&");
                    }

                }
                if (sb.Length > 0)
                {
                    sb.Remove(sb.Length - 1, 1);
                }
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(sb.ToString());

                httpWebRequest.Method = method;
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength = data.Length;
                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();
            }
        }

        /// <summary>
        /// Fills the data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="method">The method.</param>
        /// <param name="data">The data.</param>
        private void FillDataOnHttpWebRequest(HttpWebRequest httpWebRequest, string method, byte[] data)
        {
            if (httpWebRequest != null && data != null)
            {
                httpWebRequest.Method = method;
                httpWebRequest.ContentType = "text/xml; charset=utf-8";
                httpWebRequest.ContentLength = data.Length;
                Stream dataStream = httpWebRequest.GetRequestStream();
                dataStream.Write(data, 0, data.Length);
                dataStream.Close();
            }
        }

        /// <summary>
        /// Fills the data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="method">The method.</param>
        /// <param name="data">The data.</param>
        private void FillDataOnHttpWebRequest(HttpWebRequest httpWebRequest, string method, string data)
        {
            FillDataOnHttpWebRequest(httpWebRequest, method, data, null);
        }

        /// <summary>
        /// Fills the data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="method">The method.</param>
        /// <param name="data">The data.</param>
        /// <param name="encodingToByte">The encoding to byte.</param>
        private void FillDataOnHttpWebRequest(HttpWebRequest httpWebRequest, string method, string data, Encoding encodingToByte)
        {
            byte[] byteArray = null;

            if (!string.IsNullOrWhiteSpace(data))
            {
                if (encodingToByte == null)
                {
                    encodingToByte = Encoding.UTF8;
                }
                byteArray = encodingToByte.GetBytes(data);
            }

            FillDataOnHttpWebRequest(httpWebRequest, method, byteArray);
        }

        #endregion

        /// <summary>
        /// Fills post data on HttpWebRequest.
        /// </summary>
        /// <param name="httpWebRequest">The HttpWebRequest instance.</param>
        /// <param name="dataMappings">The data mappings.</param>
        public void FillPostDataOnHttpWebRequest(HttpWebRequest httpWebRequest, Dictionary<string, string> dataMappings)
        {
            FillDataOnHttpWebRequest(httpWebRequest, "POST", dataMappings);
        }

        /// <summary>
        /// Fills the post data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="data">The data.</param>
        public void FillPostDataOnHttpWebRequest(HttpWebRequest httpWebRequest, byte[] data)
        {
            FillDataOnHttpWebRequest(httpWebRequest, "POST", data);
        }

        /// <summary>
        /// Fills the post data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="data">The data.</param>
        public void FillPostDataOnHttpWebRequest(HttpWebRequest httpWebRequest, string data)
        {
            FillDataOnHttpWebRequest(httpWebRequest, "POST", data);
        }

        /// <summary>
        /// Fills the put data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="data">The data.</param>
        public void FillPutDataOnHttpWebRequest(HttpWebRequest httpWebRequest, byte[] data)
        {
            FillDataOnHttpWebRequest(httpWebRequest, "PUT", data);
        }

        /// <summary>
        /// Fills the put data on HTTP web request.
        /// </summary>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="data">The data.</param>
        public void FillPutDataOnHttpWebRequest(HttpWebRequest httpWebRequest, string data)
        {
            FillDataOnHttpWebRequest(httpWebRequest, "PUT", data);
        }

        /// <summary>
        /// Gets the post data from HTTP web request.
        /// </summary>
        /// <param name="httpRequest">The HTTP request.</param>
        /// <returns>System.Byte[][].</returns>
        public byte[] GetPostDataFromHttpWebRequest(HttpRequest httpRequest)
        {
            byte[] data = null;

            if (httpRequest != null)
            {
                MemoryStream ms = new MemoryStream();
                httpRequest.InputStream.CopyTo(ms);
                data = ms.ToArray();
            }

            return data;
        }

        /// <summary>
        /// Supply binary download via HttpResponse
        /// </summary>
        /// <param name="response"></param>
        /// <param name="physicalPath"></param>
        /// <param name="originalFullFileName"></param>
        public void SupplyBinaryDownload(HttpResponse response, string physicalPath, string originalFullFileName)
        {
            if (response != null && !string.IsNullOrWhiteSpace(physicalPath) && File.Exists(physicalPath))
            {
                if (string.IsNullOrWhiteSpace(originalFullFileName))
                {
                    originalFullFileName = "download";
                }
                FileStream fs = new FileStream(physicalPath, FileMode.Open);
                try
                {
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    response.ContentType = "application/octet-stream";
                    response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(originalFullFileName, System.Text.Encoding.UTF8));
                    response.BinaryWrite(bytes);
                    response.Flush();
                }
                catch
                {
                    throw;
                }
                finally
                {
                    fs.Close();
                    fs.Dispose();
                    response.End();
                }
            }
        }

        /// <summary>
        /// Supplies the binary download.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="physicalPath">The physical path.</param>
        /// <param name="originalFullFileName">Name of the original full file.</param>
        public void SupplyBinaryDownload(HttpContext context, string physicalPath, string originalFullFileName)
        {
            if (context != null)
            {
                SupplyBinaryDownload(context.Response, physicalPath, originalFullFileName);
            }
        }

        /// <summary>
        /// Converts the key value pair collection from string.
        /// </summary>
        /// <param name="keyValuePairString">The key value pair string.</param>
        /// <returns></returns>
        public WebDictionary ConvertKeyValuePairCollectionFromString(string keyValuePairString)
        {
            WebDictionary result = new WebDictionary();

            if (!string.IsNullOrWhiteSpace(keyValuePairString))
            {
                string[] splittedPairs = keyValuePairString.Split('&');
                foreach (var one in splittedPairs)
                {
                    if (!string.IsNullOrWhiteSpace(one))
                    {
                        string[] keyValuePair = one.Split('=');

                        if (keyValuePair.Length == 2)
                        {
                            string key = keyValuePair[0];
                            string value = keyValuePair[1];

                            if (!string.IsNullOrWhiteSpace(key))
                            {
                                if (result.ContainsKey(key))
                                {
                                    result[key] = this.GetStringValue(value);
                                }
                                else
                                {
                                    result.Add(key, this.GetStringValue(value));
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Encodes the HTML.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public string EncodeHtml(string input)
        {
            if (input == null)
            {
                input = string.Empty;
            }
            return WebUtility.HtmlEncode(input);
        }

        /// <summary>
        /// Decodes the HTML.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public string DecodeHtml(string input)
        {
            return string.IsNullOrWhiteSpace(input) ? string.Empty : WebUtility.HtmlDecode(input);
        }

        #region Protected Method

        /// <summary>
        /// Gets the stream from web response.
        /// </summary>
        /// <param name="webResponse">The web response.</param>
        /// <returns></returns>
        protected Stream GetStreamFromWebResponse(WebResponse webResponse)
        {
            Stream stream = null;
            if (webResponse != null)
            {
                stream = webResponse.GetResponseStream();
            }
            return stream;
        }

        /// <summary>
        /// Gets the type of the MIME by content.
        /// </summary>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="mimeClass">The MIME class.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <returns></returns>
        protected bool GetMimeByContentType(string contentType, out string mimeClass, out string mimeType)
        {
            mimeClass = null;
            mimeType = null;
            bool result = false;

            if (!string.IsNullOrWhiteSpace(contentType))
            {
                int index = contentType.IndexOf('/');
                if (index > 0 && index < contentType.Length - 1)
                {
                    mimeClass = contentType.Substring(0, index);
                    mimeType = contentType.Substring(index + 1);
                    result = true;
                }
            }
            return result;
        }

        #endregion

    }
}
